<?php

// 看一下该扩展中提供了那些函数
// print_r(get_extension_funcs('mongodb'));
// print_r(get_declared_classes());

const MONGODB_ADDRESS = "mongodb://localhost:27017";
const MONGODB_DBNAME = 'cdapp';

function mongo_oid($oid) {
  return new MongoDB\BSON\ObjectID($oid);
}

function mongo_insert($collection, $documents) {
  $path = MONGODB_DBNAME . '.' . $collection;
  $manager = new MongoDB\Driver\Manager(MONGODB_ADDRESS);
  $bulk = new MongoDB\Driver\BulkWrite;
  foreach ($documents as $doc) {
    // $doc['_id'] => new MongoDB\BSON\ObjectID;
    $bulk->insert($doc);
  }
  try {
    $result = $manager->executeBulkWrite($path, $bulk);
    return [
      'result' => 'success',
      'count' => $result->getInsertedCount(),
    ];
  } catch (MongoDB\Driver\Exception\BulkWriteException$e) {
    return [
      'result' => 'failed',
      'error' => $e->getWriteResult()->getWriteErrors(),
    ];
  }
}

function mongo_update($collection, $filter, $update, $upsert = false, $multi = false) {
  $path = MONGODB_DBNAME . '.' . $collection;
  $manager = new MongoDB\Driver\Manager(MONGODB_ADDRESS);
  $bulk = new MongoDB\Driver\BulkWrite;
  $bulk->update(
    $filter,
    $update,
    ['multi' => $multi, 'upsert' => $upsert]
  );
  try {
    $result = $manager->executeBulkWrite($path, $bulk);
    return [
      'result' => 'success',
      'count' => $result->getModifiedCount(),

    ];
  } catch (MongoDB\Driver\Exception\BulkWriteException$e) {
    return [
      'result' => 'failed',
      'error' => $e->getWriteResult()->getWriteErrors(),
    ];
  }
}

function mongo_delete($collection, $query) {
  $path = MONGODB_DBNAME . '.' . $collection;
  $manager = new MongoDB\Driver\Manager(MONGODB_ADDRESS);
  $bulk = new MongoDB\Driver\BulkWrite;
  $bulk->delete($query);
  try {
    $result = $manager->executeBulkWrite($path, $bulk);
    return [
      'result' => 'success',
      'count' => $result->getDeletedCount(),
    ];
  } catch (MongoDB\Driver\Exception\BulkWriteException$e) {
    return [
      'result' => 'failed',
      'error' => $e->getWriteResult()->getWriteErrors(),
    ];
  }
}

function mongo_query($collection, $filter = [], $options = []) {
  $path = MONGODB_DBNAME . '.' . $collection;
  $manager = new MongoDB\Driver\Manager(MONGODB_ADDRESS);
  $query = new MongoDB\Driver\Query($filter, $options);
  $cursor = $manager->executeQuery($path, $query);
  $data = [];
  foreach ($cursor as $document) {
    $data[] = $document;
  }
  return [
    'result' => 'success',
    'count' => count($data),
    'data' => $data,
  ];
}
